package com.orange.wwwapi.service.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.orange.core.service.user.UserService;
import com.orange.wwwapi.pojo.req.user.WxBindReq;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import java.util.Optional;

@RequiredArgsConstructor
@Service
public class WxAuthService {

    private final UserService userService;
    private final WxMaService wxMaService;

    @SneakyThrows
    public String getPhone(String code) {
        return Optional.ofNullable(wxMaService.getUserService().getPhoneNumber(code))
                .map(WxMaPhoneNumberInfo::getPurePhoneNumber)
                .orElse(null);
    }

    @SneakyThrows
    public boolean bindUser(WxBindReq req) {
        WxMaJscode2SessionResult sessionResult = wxMaService.jsCode2SessionInfo(req.getCode());
         userService.register(sessionResult.getOpenid(), sessionResult.getUnionid(), req.getPhone());
        return true;
    }
}
